package com.shanks.framework.mq.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Component
public class MQLoadConfigPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(MQLoadConfigPostProcessor.class);

    /**
     * 组件默认配置文件名
     */
    public final static String DEFAULT_CONFIG_FILE = "mq-default.properties";

    private Environment environment;
    private boolean hasInitConfigs;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        if (!hasInitConfigs) {
            try {
                loadDefaultConfigs();
            } catch (IOException e) {
                throw new RuntimeException("加载组件默认配置失败", e);
            }
            hasInitConfigs = true;
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }


    private void loadDefaultConfigs() throws IOException {
        // 1. 获取默认配置文件的输入流
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(DEFAULT_CONFIG_FILE);
        if (inputStream == null) {
            throw new FileNotFoundException("默认配置文件未找到: " + DEFAULT_CONFIG_FILE);
        }

        // 2. 加载配置文件
        Properties properties = new Properties();
        properties.load(inputStream);

        // 3. 将配置文件的内容加载到 Spring 环境中
        MutablePropertySources propertySources = ((ConfigurableEnvironment) environment).getPropertySources();
        propertySources.addFirst(new PropertiesPropertySource("mqDefaultConfig", properties));

        // 4. 关闭输入流
        inputStream.close();

        logger.info("默认配置文件加载成功: {}", DEFAULT_CONFIG_FILE);
    }
}

